package com.bdhub.tools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * GZIP压缩解压类
 */
public class MessageGZIP {
	private static String encode = "utf-8";// "ISO-8859-1"

	public String getEncode() {
		return encode;
	}

	/*
	 * 设置 编码，默认编码：UTF-8
	 */
	public void setEncode(String encode) {
		MessageGZIP.encode = encode;
	}

	/*
	 * 字符串压缩为字节数组
	 */
	public static String compressTo(String str) {
		return compressTo(str, encode);
	}

	/*
	 * 字符串压缩为另一字符串
	 */
	public static String compressTo(String str, String encoding) {
		if (str == null || str.length() == 0) {
			return "";
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip;
		try {
			gzip = new GZIPOutputStream(out);
			gzip.write(str.getBytes(encode));
			gzip.close();
			return out.toString("ISO-8859-1");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	/*
	 * 将字符串解压缩后返回字符串
	 */
	public static String uncompressToString(String b) {
		return uncompressToString(b, encode);
	}

	/*
	 * 将字符串解压缩后返回字符串
	 */
	public static String uncompressToString(String b, String encoding) {
		if (b == null || b.length() == 0) {
			return "";
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = null;
		try {
			in = new ByteArrayInputStream(b.getBytes("ISO-8859-1"));
			GZIPInputStream gunzip = new GZIPInputStream(in);
			byte[] buffer = new byte[256];
			int n;
			while ((n = gunzip.read(buffer)) >= 0) {
				out.write(buffer, 0, n);
			}
			return out.toString(encode);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "";
	}

	public static void main(String[] args) {
//		long time= System.currentTimeMillis();
//		String str = "aaaaaaaaaaaaaaaaaaaddddddddddddddddddd劳而无功中国人大中国asdfdasfdasf恭恭敬敬恭恭敬敬恭恭敬敬恭恭敬敬恭恭敬敬恭恭敬敬aadfdfdasfa恭恭敬敬恭恭敬敬aaa";
//		System.out.println("原长度：" + str.length());
//		String str1 = MessageGZIP.compressTo(str);
//		try {
//			System.out.println(new String(Base64.decode(str1, 0),"utf-8"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		System.out.println("压缩后长度:" + str1.length());
//		System.out.println(MessageGZIP.uncompressToString(str1));
//		System.out.println(System.currentTimeMillis()- time);
	}
}